package com.cn.transfer.handle.impl.saledelivery;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.*;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.common.vo.MessagePushVO;
import com.cn.transfer.handle.MessageStrategy;
import com.cn.transfer.mapper.VvSaSaleDeliveryBMapper;
import com.cn.transfer.mapper.VvSaSaleDeliveryMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 向伟典
 * @date: 2023/10/7 15:23
 * @Description: 销货单审核时
 */
@Slf4j
@Component
public class SaledeliveryReviewImpl implements MessageStrategy {
    @Autowired
    private VvSaSaleDeliveryMapper vvSaSaleDeliveryMapper;
    @Autowired
    private VvSaSaleDeliveryBMapper vvSaSaleDeliveryBMapper;


    @Transactional
    @Override
    public void handle(MessagePushVO message) {
        DocumentApproval documentApproval = ConnmeUtils.mapToObject(message.getBizContent(), DocumentApproval.class);
        VvSaSaleDelivery vvSaSaleDelivery = vvSaSaleDeliveryMapper.byCode(documentApproval.getVoucherCode());
        // 查询视图，这条数据是否存在
        int i1 = vvSaSaleDeliveryMapper.inquireIsExist(vvSaSaleDelivery.getDocumentcode());
        if (i1 == 0) {
            // 存入视图
            vvSaSaleDeliveryMapper.insertVvSaSaleDelivery(vvSaSaleDelivery);
            for (VvSaSaleDeliveryB vvSaSaleDeliveryB : vvSaSaleDelivery.getVvsasaledeliveryblist()) {
                vvSaSaleDeliveryBMapper.insertVvSaSaleDeliveryB(vvSaSaleDeliveryB);
            }
        }
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "6500165a60a971000ab0ad28");
        parameter.put("entry_id", "6520efcb35a3c4a7355b275d");
        parameter.put("data", ConnmeUtils.convertEntityToMap(vvSaSaleDelivery));
        String jsonSale = JSONUtil.toJsonStr(parameter);
        log.info("销货单审核时发生的数据：==== " + jsonSale);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
        log.info("销货单审核时接收的数据：====" + jdySale);
    }

    @Override
    public String getMsgType() {
        return "SaleDelivery_Audit";
    }
}
